<?php
/**
 * Created by PhpStorm.
 * User: frank
 * Date: 2019-03-15
 * Time: 9:36
 */

namespace App\Http\Controllers\Auth;

use Cache;
use Auth;
use App\Models\User as Usr;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;

trait MyAuthTrait
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login-admin');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $users = Usr::all();
        $onlines = 0;
        foreach ($users as $user) {
            if ($user->isOnline()) {
                $onlines = $onlines + 1;
            }
        }
        $licFile = public_path('uploads/lic/license.dat');
        if (file_exists($licFile)) {
            $lic = unserialize(base64_decode(file_get_contents($licFile)));
            if ($onlines >= $lic['allow_user']) {
                return back()->withErrors('超过最大允许同时在线用户数');
            }
        } else {
            return back()->withErrors('没有找到许可证文件');
        }
        $this->validateLogin($request);
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }
        if (Auth::attempt(['email'=>$request->input('email'),'password'=>$request->input('password'),'active'=>1],$request->filled('remember'))) {
            /*尝试登录通过，那么更新user 表中的$api_token字段*/
            $user = Auth::user();
            $api_token = uniqid($user->id);
            $user->api_token = $api_token;
            $user->save();
            return $this->sendLoginResponse($request);

        } else
        {
            return back()->withErrors('用户名密码错误或者账户未激活，请找系统管理员处理');
        }
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }


    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request $request
     * @return void
     */
    protected
    function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return bool
     */
    protected
    function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    protected
    function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected
    function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();
        $this->clearLoginAttempts($request);
        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  mixed $user
     * @return mixed
     */
    protected
    function authenticated(Request $request, $user)
    {
        \Debugbar::info('authenticated');
        /*下面的代码可以实现单点登录,前提条件是user 表中要添加session_id字段,这样才能保存session_id*/
        $previous_session = $user->session_id;
        if ($previous_session) {
            \Session::getHandler()->destroy($previous_session);
        }
        \Auth::user()->session_id = \Session::getId();
        \Auth::user()->save();
        return redirect()->intended($this->redirectPath());
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws ValidationException
     */
    protected
    function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public
    function username()
    {
        return 'email';
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public
    function logout(Request $request)
    {
        Cache::pull('user-is-online-' . Auth::user()->id);
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/login');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected
    function guard()
    {
        return Auth::guard();
    }
}
